package com.linln.wxapi;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.linln.common.constant.NoticeTypeConst;
import com.linln.modules.message.domain.MessageInfo;
import com.linln.modules.message.domain.MessageRefund;
import com.linln.modules.message.service.MessageInfoService;
import com.linln.modules.message.service.MessageRefundService;
import com.linln.modules.tribe.domain.Tribe;
import com.linln.wxapi.config.WxMaConfiguration;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.linln.common.enums.TypeEnum;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.vo.ResultVo;
import com.linln.modules.member.domain.MemberInfo;
import com.linln.modules.member.service.MemberInfoService;
import com.linln.modules.modules.reply.domain.Reply;
import com.linln.modules.modules.reply.service.ReplyService;
import com.linln.modules.store.service.StoreinfoService;
import com.linln.modules.tribe.service.TribeService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 *  评论接口
 * @author hct
 *
 */
@Api(value="评论列表")
@RestController
@RequestMapping("/wx/reply/{area}")
public class WxApiReplyController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ReplyService replyService;
    @Autowired
    private MemberInfoService memberService;
    
    @Autowired
    private TribeService tribeService;
    
    @Autowired
    private StoreinfoService storeService;

    @Autowired
    private MessageInfoService messageService;
    @Autowired
    private MessageRefundService messageRefundServiceImpl;
    
   /**
    * 
    * @param area
    * @param typeid
    * @param type
    * @return
    */
 	@ApiOperation(value = "获取评论信息",  notes = "获取评论信息")
     @ApiImplicitParams({
          @ApiImplicitParam(name = "typeid", value = "类型id ：",paramType = "query", required = true, dataType = "int"),
          @ApiImplicitParam(name = "type", value = "类型",paramType = "query", required = true, dataType = "int")
          
     })
     @RequestMapping(value = "list",method={RequestMethod.POST,RequestMethod.GET})
     @ResponseBody
     public ResultVo replylist(@PathVariable String area, Long typeid, Integer type) {
        
         try {
         	// 创建匹配器，进行动态查询匹配
             ExampleMatcher matcher = ExampleMatcher.matching()
            		// .withMatcher("area", match -> match.equals(area))
                     .withMatcher("type", match -> match.equals(type))
                     .withMatcher("typeid", match -> match.equals(typeid));
                     
             Reply reply=new Reply();
             reply.setType(type);
           //  reply.setArea(area); 
             reply.setTypeid(typeid);
             // 获取数据列表
             Example<Reply> example = Example.of(reply, matcher);
            // Sort sort = new Sort(Sort.Direction.ASC, "num");
             Page<Reply> list = replyService.getPageList(example);
             Map<String,Object> map=new HashMap<String,Object>();
             map.put("list", list.getContent());
             map.put("pageNumber", list.getPageable().getPageNumber()+1);
             map.put("pageSize", list.getPageable().getPageSize());
             return ResultVoUtil.success(map);
         } catch (Exception e) {
             this.logger.error(e.getMessage(), e);
             return ResultVoUtil.error("接口异常"); 
         }
     }
    
     
     /**
      * 回复信息
      * @param area 区域
      * @param
      * @param
      * @return
      */
     @ApiOperation(value = "回复",  notes = "回复")
     @RequestMapping(value = "fabu",method=RequestMethod.POST)
     @ResponseBody
     public ResultVo replyfabu(@PathVariable String area,Reply reply) {
        
         try {
             if(!checkMsg(reply.getContent())) {
                 return ResultVoUtil.error("违规内容");
             }else {
                 System.out.println("我正规");
             }
        	MemberInfo member= memberService.getById(reply.getMemberid());
        	 reply.setNickname(member.getNickname());
        	 reply.setHead(member.getHeadimg());
             reply = replyService.save(reply);
             if(reply.getType()==TypeEnum.MESSAGE.getCode()) {
            	//
             }else if(reply.getType()==TypeEnum.TRIBE.getCode()) {
            	 tribeService.updateIsReplyAddById(reply.getTypeid());
             }
             else if(reply.getType()==TypeEnum.STORE.getCode()) {
            	 storeService.updateReplyAddById(reply.getTypeid());    	 
             }

             MessageRefund message=new MessageRefund();
           if(reply.getType()==TypeEnum.TRIBE.getCode()) {
                 Tribe tribe=tribeService.getById(reply.getTypeid());
               message.setMemberId(reply.getMemberid());
               message.setMessageId(tribe.getId());
               message.setStatus(0);
               message.setType(NoticeTypeConst.REPLY);
               message.setContent("评论提醒：您发布的消息"+ (StringUtils.isEmpty(tribe.getTitle()) ? "":tribe.getTitle()) +"有评论,请及时查看~");
               message.setCreateDate(new Date());
               message.setUpdateDate(new Date());
               messageRefundServiceImpl.saveMessageRefund(message);
           }else{
               MessageInfo messageInfo = messageService.getById(reply.getTypeid());
               message.setMemberId(reply.getMemberid());
               message.setMessageId(messageInfo==null?0:messageInfo.getId());
               message.setStatus(0);
               message.setType(NoticeTypeConst.REPLY);
               message.setContent("评论提醒：您发布的消息"+ (StringUtils.isEmpty(messageInfo.getTitle()) ? "":messageInfo.getTitle()) +"有评论,请及时查看~");
               message.setCreateDate(new Date());
               message.setUpdateDate(new Date());
               messageRefundServiceImpl.saveMessageRefund(message);
           }
             return ResultVoUtil.success(reply);


         } catch (Exception e) {
             this.logger.error(e.getMessage(), e);
             return ResultVoUtil.error("接口异常"); 
         }
  
     }

    public Boolean checkMsg(String content) throws WxErrorException, IOException {
        WxMaService wxService = WxMaConfiguration.getWxMaService();
        System.out.println("wxService====="+wxService);
        String token=wxService.getAccessToken();
        System.out.print("token====="+token);
        Map<String, String> map = new HashMap<>();
        String url="https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" +token;
        map.put("content", content);
        Map<String, String> contentmap = new HashMap<String, String>();
        contentmap.put("content", content);
        String json = JSONObject.toJSONString(contentmap);
        System.out.println("json is = "+json);
        JSONObject msg = doPost(url, json);
        if(((Integer)msg.get("errcode")).intValue()==0 && msg.get("errmsg").toString().equals("ok")){
            //代表正常
           return true;
        }else{
            return false;
        }
    }

    public static void main(String[] args) throws WxErrorException, IOException {
        WxApiReplyController a=new WxApiReplyController();
        a.checkMsg("aa");
    }

    /**
     * post请求
     * @param url
     * @param json
     * @return
     */
    public static JSONObject doPost(String url,String json){

        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        JSONObject response = null;
        try {
            StringEntity s = new StringEntity(json,"UTF-8");
            s.setContentEncoding("UTF-8");
            s.setContentType("application/json");//发送json数据需要设置contentType
            post.setEntity(s);
            System.out.println(post);
            HttpResponse res = httpclient.execute(post);
            if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                String result = EntityUtils.toString(res.getEntity());// 返回json格式：
                response = JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return response;
    }
}
